﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Net.Mail;

public partial class index : System.Web.UI.Page
{
    protected StringBuilder sb = new StringBuilder();
    BLL.Users blluser = new BLL.Users();
    protected MODEL.Users model = new MODEL.Users();
    protected BLL.LostAndFound blllaf = new BLL.LostAndFound();
    protected BLL.Search bllsearch = new BLL.Search();
    protected void Page_Load(object sender, EventArgs e)
    {
        #region 绑定 加载热词
        //绑定 加载热词
        if (common.getKeyWord() != null)
        {
            rpHotWords.DataSource = common.getKeyWord();
            rpHotWords.DataBind();
        } 
        #endregion

        //判断是否访问(登录过session不为空)，是否记住我
        if (!IsPostBack)
        {
            if (!common.isLoginOrNot())
            {
                modify.Visible = false;
                logOut.Visible = false;
            }
            else
            {
                //session不为null则显示
                show();
            }
        }

        #region 绑定数据tb1
        //绑定数据tb1
        List<MODEL.LostAndFound> models = new List<MODEL.LostAndFound>();
        models = blllaf.getAll("", 1, "Time desc");
        foreach (MODEL.LostAndFound laf in models)
        {
            if (laf.Feature.Length > 12)
                laf.Feature =Server.HtmlEncode((laf.Feature.Substring(0, 12) + "......"));
        }
        rpLAF.DataSource = models;
        rpLAF.DataBind(); 
        #endregion

        #region tb2
        //tb2
        List<MODEL.LostAndFound> models1 = new List<MODEL.LostAndFound>();
        models1 = blllaf.getAll("寻物启事", 1, "Time desc");
        foreach (MODEL.LostAndFound laf in models1)
        {
            if (laf.Feature.Length > 12)
                laf.Feature = laf.Feature.Substring(0, 12) + "......";
        }
        rpFound.DataSource = models1;
        rpFound.DataBind(); 
        #endregion

        #region tb3
        //tb3
        List<MODEL.LostAndFound> models2 = new List<MODEL.LostAndFound>();
        models2 = blllaf.getAll("招领启事", 1, "Time desc");
        foreach (MODEL.LostAndFound laf in models2)
        {
            if (laf.Feature.Length > 12)
                laf.Feature = laf.Feature.Substring(0, 12) + "......";
        }
        rpGet.DataSource = models2;
        rpGet.DataBind(); 
        #endregion
    }

    #region 注册
    /// <summary>
    /// 注册
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void register_Click(object sender, EventArgs e)
    {
        Response.Redirect("register.aspx");//注册按钮点击重定向到注册页面
    } 
    #endregion

    #region 登录
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void login_Click(object sender, EventArgs e)
    {
        string name = txtName.Value.Trim();
        string pwd;
        //根据name判断是否为管理员，如果是的话不用MD5加密然后再验证
        MODEL.Users User = new MODEL.Users();
        User = blluser.getModel(name);
        if (User != null)
        {
            if (User.UserRoleId == 2 || User.UserRoleId == 3)
            {
                pwd = txtPwd.Value.Trim();
            }

            //否则加密再验证
            else
            {
                pwd = common.GetMD5(txtPwd.Value.Trim());
            }

            //登录(用户名，密码正确则登录成功)
            if (blluser.Exist(name, pwd))
            {
                model = blluser.getModel(name);
                if (model != null)
                {
                    //把model实体对象保存到session中
                    Session["currentUser"] = model;
                    if (cbRemember.Checked)
                    {
                        HttpCookie cookieName = new HttpCookie("name", model.UName);
                        HttpCookie cookiePwd = new HttpCookie("pwd", common.Encrypt(model.Pwd, ""));
                        cookieName.Expires = DateTime.Now.AddYears(1);
                        cookiePwd.Expires = DateTime.Now.AddYears(1);
                        Response.Cookies.Add(cookieName);
                        Response.Cookies.Add(cookiePwd);
                    }
                    show();
                }
            }
            else
            {
                MessageBox.Show(this, "用户名或密码有错");
            }
        }
        else
        {
            MessageBox.Show(this, "用户名不存在");
        }
    } 
    #endregion

    #region 对控件的隐藏显示操作
    public void show()
    {
        retrieve.Visible = false;
        contentRT1.Visible = false;
        modify.Visible = true;
        //注意这里得用session来取id的值，不要直接有model
        modify.HRef = "modify.aspx?id=" + ((MODEL.Users)Session["currentUser"]).UId;
        logOut.Visible = true;
        //MessageBox.Redirect(this, "window.location=\"index.aspx\";");
        sb.Append("<marquee direction='up' scrolldelay='300' height='120px'><font size='4px'>欢迎您" + ((MODEL.Users)Session["currentUser"]).UName + "光临本站！</font></marquee>");
    } 
    #endregion

    #region 退出
    /// <summary>
    /// 退出
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void logOut_Click(object sender, EventArgs e)
    {
        common.LoginOut();
        //别忘了重定向到首页
        Response.Redirect("index.aspx");
    } 
    #endregion

    #region 提交（通过邮件重置密码）
    /// <summary>
    /// 提交（通过邮件重置密码）
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void divSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string name=divUsername.Value.Trim();
            string question=divDropDL.SelectedItem.Text.Trim();
            string answer = divAnswer.Value.Trim();
            if (blluser.isExistOrNotByQA(name, question, answer))
            {
                MODEL.Users model = blluser.getModel(name);
                try
                {
                    Mail.sendMail(model.Email, name);
                    MessageBox.Show(this, "系统为您重置的密码已经发送到您的邮箱");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "发送邮件出现异常");
                    throw new Exception(ex.Message);
                } 
            }
            else
            {
                MessageBox.Show(this, "用户名不存在或密保问题有错，答案不正确");
            }
        }
    } 
    #endregion

    #region 搜索
    /// <summary>
    /// 搜索
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSearch_Click(object sender, ImageClickEventArgs e)
    {
        //将搜索的词汇加入到数据库
        try
        {
            bllsearch.addKeyWord(txtSearch.Value);
        }
        catch(Exception ex)
        {
            throw new Exception(ex.Message);
        }
        Response.Redirect("searchResults.aspx?keyword=" + txtSearch.Value);
    } 
    #endregion
}